// Package middleware 参数获取模块
package middleware

import (
	"bytes"
	"io"
	"regexp"
	"strconv"
	"strings"

	"github.com/gin-gonic/gin"
)

// Args 获取字符串参数，转移并清除html代码
func Args(ctx *gin.Context, str string) string {
	var funMid *FunMiddleWare
	json := ""
	types := strings.ToLower(ctx.Request.Header.Get("Content-Type"))
	if strings.Index(types, "json") != -1 {
		body, _ := io.ReadAll(ctx.Request.Body)
		ctx.Request.Body = io.NopCloser(bytes.NewBuffer(body))
		json = Json_decode_string(string(body), str)
	}
	cookie, _ := ctx.Cookie(str)
	lists := map[string]string{
		"header": ctx.Request.Header.Get(str),
		"param":  ctx.Param(str),
		"get":    ctx.DefaultQuery(str, ""),
		"post":   ctx.DefaultPostForm(str, ""),
		"json":   json,
		"cookie": cookie,
	}

	for key := range lists {
		if lists[key] != "" && lists != nil {
			return funMid.TrimHtml(Addslashes(lists[key]))
		}
	}
	return ""
}

// Argi 获取int参数
func Argi(ctx *gin.Context, str string) int {
	args := Args(ctx, str)
	argi, _ := strconv.Atoi(args)
	return argi
}

// Addslashes 转义
func Addslashes(str string) string {
	tmpRune := []rune{}
	strRune := []rune(str)
	for _, ch := range strRune {
		switch ch {
		case []rune{'\\'}[0], []rune{'"'}[0], []rune{'\''}[0]:
			tmpRune = append(tmpRune, []rune{'\\'}[0])
			tmpRune = append(tmpRune, ch)
		default:
			tmpRune = append(tmpRune, ch)
		}
	}
	return UnicodeEmojiCode(string(tmpRune))
}

// Stripslashes 反转义
func Stripslashes(str string) string {
	dstRune := []rune{}
	strRune := []rune(str)
	strLenth := len(strRune)
	for i := 0; i < strLenth; i++ {
		if strRune[i] == []rune{'\\'}[0] {
			i++
		}
		dstRune = append(dstRune, strRune[i])
	}
	return UnicodeEmojiDecode(string(dstRune))
}

// UnicodeEmojiDecode 表情解码
func UnicodeEmojiDecode(s string) string {
	//emoji表情的数据表达式
	re := regexp.MustCompile("\\[[u0-9a-zA-Z]+]")
	//提取emoji数据表达式
	reg := regexp.MustCompile("\\[u|]")
	src := re.FindAllString(s, -1)
	for i := 0; i < len(src); i++ {
		e := reg.ReplaceAllString(src[i], "")
		p, err := strconv.ParseInt(e, 16, 32)
		if err == nil {
			s = strings.Replace(s, src[i], string(rune(p)), -1)
		}
	}
	return s
}

// UnicodeEmojiCode 表情转换
func UnicodeEmojiCode(s string) string {
	ret := ""
	rs := []rune(s)
	for i := 0; i < len(rs); i++ {
		if len(string(rs[i])) == 4 {
			u := `[u` + strconv.FormatInt(int64(rs[i]), 16) + `]`
			ret += u

		} else {
			ret += string(rs[i])
		}
	}
	return ret
}
